package com.av.client.frames;

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyVetoException;
import java.util.logging.Level;

import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import org.jdesktop.swingx.JXErrorPane;
import org.jdesktop.swingx.error.ErrorInfo;

import com.av.client.components.AvButton;
import com.av.client.components.AvComponent;
import com.av.client.components.AvLabel;
import com.av.client.util.idioma.Etiqueta;
import com.av.client.util.idioma.ManejadorIdiomas;
import com.av.client.util.idioma.ManejadorIdiomas.IdiomaEvent;
import com.av.client.util.idioma.ManejadorIdiomas.IdiomaEventListener;
import com.av.client.util.sesion.AdministradorSesion;
import com.av.client.util.sesion.SesionCreador;
import com.av.db.dataobjects.enums.Rol;
import com.av.exceptions.AvException;

/**
 * Clase utilizada para el control de inicio de sesion del usuario
 * 
 * @author Victor J Morales R
 * 
 */
@SuppressWarnings("serial")
public class LoginFrame extends JInternalFrame {

	private static final int WIDTH = 350;
	private static final int HEIGHT = 200;
	private static final boolean VALIDAR_PASSWORD = false;

	private static LoginFrame instance;

	private AvLabel lblUsuario;
	private AvLabel lblPassword;
	private AvLabel lblServidor;
	private JTextField txtUsuario;
	private JTextField txtPassword;
	private JTextField txtHost;
	private AvButton btnAceptar;
	private AvButton btnCancelar;

	private ManejadorIdiomas mi;

	public static LoginFrame getInstance() {
		if (instance == null) {
			instance = new LoginFrame();
		}

		return instance;
	}// getInstance

	private LoginFrame() {
		super();
		mi = ManejadorIdiomas.getInstance();
		initComponents();
		addListeners();
		cargarPermisos();
	}// LoginFrame

	/**
	 * Funcion que habilita o deshabilita los componentes de acuerdo a sus
	 * permisos asignados
	 */
	private void cargarPermisos() {
		if (AdministradorSesion.getInstance().getSesionActiva() != null) {
			Rol r = AdministradorSesion.getInstance().getSesionActiva()
					.getUsuario().getRol();
			for (Component c : this.getContentPane().getComponents()) {
				if (c instanceof JPanel) {
					for (Component c2 : ((JPanel) c).getComponents()) {
						if (c2 instanceof AvComponent) {
							c2.setEnabled(((AvComponent) c2).contains(r));
						}
					}
				} else if (c instanceof AvComponent) {
					c.setEnabled(((AvComponent) c).contains(r));
				}
			}
		}
	}// cargarPermisos

	private void addListeners() {
		mi.addIdiomaEventListener(new IdiomaEventListener() {
			@Override
			public void changedIdiomaEvent(IdiomaEvent evt) {
				setLabels();
			}
		});
	}// addListeners

	/**
	 * Funcion que restablece las etiquetas para todos los componentes
	 */
	private void setLabels() {
		setTitle(mi.obtenerEtiqueta(Etiqueta.LOGING_FRAME_TITLE));
		lblUsuario.setText(Etiqueta.LOGING_FRAME_LBL_USUARIO);
		lblPassword.setText(Etiqueta.LOGING_FRAME_LBL_CONTRASENIA);
		lblServidor.setText(Etiqueta.LOGING_FRAME_LBL_SERVIDOR);
		btnAceptar.setText(Etiqueta.LOGING_FRAME_BTN_ACEPTAR);
		btnCancelar.setText(Etiqueta.LOGING_FRAME_BTN_CANCELAR);
	}// setLabels

	private void initComponents() {
		setTitle(mi.obtenerEtiqueta(Etiqueta.LOGING_FRAME_TITLE));
		setLayout(new GridBagLayout());
		GridBagConstraints gc = new GridBagConstraints();

		gc.insets = new Insets(5, 5, 5, 5);
		gc.fill = GridBagConstraints.HORIZONTAL;

		// Usuario
		gc.gridy = 0;
		gc.gridx = 0;
		gc.weightx = 0.0;
		lblUsuario = new AvLabel(Etiqueta.LOGING_FRAME_LBL_USUARIO);
		add(lblUsuario, gc);

		gc.gridx = 1;
		gc.weightx = 1.0;
		txtUsuario = new JTextField();
		add(txtUsuario, gc);

		// Password
		gc.gridy = 1;
		gc.gridx = 0;
		gc.weightx = 0.0;
		lblPassword = new AvLabel(Etiqueta.LOGING_FRAME_LBL_CONTRASENIA);
		add(lblPassword, gc);

		gc.gridx = 1;
		gc.weightx = 1.0;
		txtPassword = new JPasswordField();
		add(txtPassword, gc);

		// Host
		gc.gridy = 2;
		gc.gridx = 0;
		gc.weightx = 0.0;
		lblServidor = new AvLabel(Etiqueta.LOGING_FRAME_LBL_SERVIDOR);
		add(lblServidor, gc);

		gc.gridx = 1;
		gc.weightx = 1.0;
		txtHost = new JTextField();
		add(txtHost, gc);

		// Botones
		JPanel tmp = new JPanel();

		btnAceptar = new AvButton(Etiqueta.LOGING_FRAME_BTN_ACEPTAR);
		btnAceptar.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				try {
					validarTextos();
				} catch (AvException e1) {
					ErrorInfo info = new ErrorInfo(getTitle() + " - ERROR", e1
							.getMessage(), null, null, e1, Level.ALL, null);
					JXErrorPane.setDefaultLocale(mi.getIdioma().getLocale());
					JXErrorPane.showDialog(getParent(), info);
					return;
				}

				SesionCreador sf = SesionCreador.getInstance();
				SesionCreador.setHost(txtHost.getText());
				SesionCreador.setComprimir(true);
				try {
					AdministradorSesion.getInstance().setSesionActiva(
							sf.getSession(txtUsuario.getText(), txtPassword
									.getText()));
					setVisible(false);
					limpiarTextos();
				} catch (AvException e1) {
					ErrorInfo info = new ErrorInfo(getTitle() + " - ERROR", e1
							.getMessage(), null, null, e1, Level.SEVERE, null);
					JXErrorPane.setDefaultLocale(mi.getIdioma().getLocale());
					JXErrorPane.showDialog(getParent(), info);
				}
			}
		});
		btnAceptar.loadPermisos();
		tmp.add(btnAceptar);

		btnCancelar = new AvButton(Etiqueta.LOGING_FRAME_BTN_CANCELAR);
		btnCancelar.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				setVisible(false);
			}
		});
		btnCancelar.loadPermisos();
		tmp.add(btnCancelar);

		gc.gridx = 0;
		gc.gridy = 3;
		gc.gridwidth = 2;
		gc.weightx = 1.0;
		add(tmp, gc);

		setClosable(false);
		setSize(WIDTH, HEIGHT);
	}// initComponents

	/**
	 * Funcion que borra todos los campos del formulario
	 */
	private void limpiarTextos() {
		txtUsuario.setText("");
		txtPassword.setText("");
		txtHost.setText("");
	}// limpiarTextos

	public void setVisible(boolean visible) {
		super.setVisible(visible);

		if (instance != null) {
			try {
				instance.setSelected(visible);
			} catch (PropertyVetoException e) {
			}
		}

		if (txtUsuario != null) {
			txtUsuario.requestFocus();
		}
	}// setVisible

	private void validarTextos() throws AvException {
		if (txtUsuario.getText() == null
				|| txtUsuario.getText().trim().length() == 0) {
			txtUsuario.requestFocus();
			throw new AvException("Ingrese un usuario");
		}

		if (VALIDAR_PASSWORD) {
			if (txtPassword.getText() == null
					|| txtPassword.getText().trim().length() == 0) {
				txtPassword.requestFocus();
				throw new AvException("Ingrese un password");
			}
		}
	}// validarTextos

	public static void main(String[] args) {
		JFrame tmp = new JFrame("Test");
		tmp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		JDesktopPane desktop = new JDesktopPane();
		desktop.setBackground(Color.GRAY);
		desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
		tmp.setContentPane(desktop);

		LoginFrame ea = new LoginFrame();
		ea.setVisible(true);
		desktop.add(ea);
		try {
			ea.setSelected(true);
		} catch (PropertyVetoException e) {
		}
		tmp.setSize(new Dimension(ea.getWidth() + 100, ea.getHeight() + 100));
		tmp.setVisible(true);
	}// main
}// LoginFrame